//
//  YWNewMyTroubleCell.m
//  maintain
//
//  Created by 郑想 on 16/7/23.
//  Copyright © 2016年 ewin. All rights reserved.
//

#import "YWMyPostTroubleCell.h"
#import "UIImageView+WebCache.h"
#import "YWCommonTool.h"
#import "YWHandler.h"
#import "YWMission.h"
#import "YWBuilding.h"
#import "YWBuildingManager.h"
#import "YWEquipmentManager.h"
#import "YWMissionManager.h"
#import "YWMacro.h"
#import "Masonry.h"
#import "UIColor+CustomColors.h"
#import "YWEquipment.h"
#import "YWReportTroubleModel.h"
#import "YWLocation.h"
#import "YWFloor.h"
#import "YWApartment.h"
#import "YWEquipmentType.h"
#import "YYLabel.h"
#import "YWContactManager.h"
#import "YWReplyManager.h"
#import "YWReply.h"

@interface YWMyPostTroubleCell()
/** 状态Label */
@property (nonatomic, strong) YYLabel *stateLabel;
/** 报障人头像 */
@property (nonatomic, strong) UIImageView *reporterImageView;
/** 报障人 */
@property (nonatomic, strong) YYLabel *reporterName;
/** 任务创建时间 */
@property (nonatomic, strong) YYLabel *createTime;
/** 保障编号 */
@property (nonatomic, strong) YYLabel *bianhao;
/** 设备类型 */
@property (nonatomic, strong) YYLabel *equipmentLabel;
/** 设备位置 */
@property (nonatomic, strong) YYLabel *location;
/** 报障描述 */
@property (nonatomic, strong) YYLabel *note;

///** 备注与参与人分割线 */
//@property (nonatomic, strong) UIView *separatorLineView;
///** 参与人 */
//@property (nonatomic, strong) YYLabel *observersLabel;
///** last评论 */
//@property (nonatomic, strong) YYLabel *replyLabel;
/** 报障现场图片 */
//@property (nonatomic, strong) NSArray *pictures;
/** 图片容器 */
//@property (weak, nonatomic) GropPictureView *picturesView;
/** 图片高的约束 */
//@property (nonatomic, strong) MASConstraint *picHeightConstraint;
@property (nonatomic, strong) NSString *stateString;

@end

@implementation YWMyPostTroubleCell

+ (instancetype)cellWithTableView:(UITableView *)tableView
{
    YWMyPostTroubleCell *cell = [tableView dequeueReusableCellWithIdentifier:YWMyPostTroubleCellIdentifier];
    if (cell == nil) {
        cell = [[YWMyPostTroubleCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:YWMyPostTroubleCellIdentifier];
    }
    return cell;
}

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        self.layer.shouldRasterize = YES;
        self.layer.rasterizationScale = [UIScreen mainScreen].scale;
        [self setUpSubviews];
        self.selectionStyle = UITableViewCellSelectionStyleNone;
        self.clipsToBounds = YES;
    }
    return self;
}


- (void)setReportTrouble:(YWReportTroubleModel *)reportTrouble{
    _reportTrouble = reportTrouble;
    YWHandler *fromUser = nil;
    NSString *location = nil;
    
    if (reportTrouble.channel == YWPostTroubleTypeEwinApp) {
        fromUser = reportTrouble.reporter;
    }else{
        fromUser = [[YWHandler alloc] init];
        fromUser.userName = reportTrouble.troubleContact.contactName;
        fromUser.mobile = reportTrouble.troubleContact.contactNo;
    }
    if (reportTrouble.equipment.equipmentId.length) {
        YWEquipment* equipment = reportTrouble.equipment;//[[YWEquipmentManager shareManager] equipmentWithId:reportTrouble.equipment.equipmentId];
        location = equipment ? [[YWBuildingManager shareManager] equipmentLocation:equipment] : nil;
    }
    if (location.length==0 && reportTrouble.location.locationId) {
        location = [[YWBuildingManager shareManager] areaLocationWithLocationId:reportTrouble.location.locationId];
    }
    
    NSString* downloadUrl = [YWCommonTool pictureDownloadUrl:fromUser.headIcon];
    [_reporterImageView sd_setImageWithURL:[NSURL URLWithString:downloadUrl] placeholderImage:[UIImage imageNamed:@"profile_headimage"]];
    
    NSString *name = fromUser.userName.length?fromUser.userName:@"无";
    _reporterName.text = name;
    
    NSString* reportTimeStr = [YWCommonTool showTimeWithNormalFormatter:reportTrouble.reportTime / 1000];
    _createTime.text = reportTimeStr;
    
    NSString *troubleSequence = [NSString stringWithFormat:@"%@",reportTrouble.troubleSequence?:@"无"];
    _bianhao.attributedText = [YWCommonTool attributedTextWithFirstText:@"编号: " firstColor:[UIColor customTextGrayBlackColor] secondText:troubleSequence secondColor:[UIColor customYellowColor] font:kContentFont];
    NSString *equipmentName = nil;
    if (reportTrouble.equipment) {
        equipmentName = reportTrouble.equipment.equipmentName?:@"无";//([[YWEquipmentManager shareManager] equipmentWithId:_troubleMission.equipmentId].equipmentName?:@"无");
    }else if (reportTrouble.equipmentType){
        equipmentName = reportTrouble.equipmentType.equipmentTypeName?:@"无";// [[YWEquipmentManager shareManager] equipmentTypeNameWithTypeId:_troubleMission.equipmentTypeId];
    }
    _equipmentLabel.attributedText = [YWCommonTool attributedTextWithFirstText:@"设备: " firstColor:[UIColor customTextGrayBlackColor] secondText:equipmentName.length?equipmentName:@"无" secondColor:[UIColor blackColor] font:kContentFont];
    _location.attributedText = [YWCommonTool attributedTextWithFirstText:@"位置: " firstColor:[UIColor customTextGrayBlackColor] secondText:location.length?location:@"无" secondColor:[UIColor blackColor] font:kContentFont];
    _note.attributedText = [YWCommonTool attributedTextWithFirstText:@"说明: " firstColor:[UIColor customTextGrayBlackColor] secondText:reportTrouble.note?:@"无" secondColor:[UIColor blackColor] font:kContentFont];
    
    //    _pictures = [[YWMissionManager shareManager] picturesWithTroubleMissionId:troubleMission.troubleId pictureTroubleType:YWPictureTroubleTypeMission];
    //    [_picturesView initWithGroupItems:_pictures withConstraint:nil];
    //任务状态Label
    _stateLabel.text = self.stateString;
    if (reportTrouble.troubleStatus == YWTroubleMissionStatusAssign) {
        _stateLabel.textColor = [UIColor customTextGrayColor];
    }else{
        _stateLabel.textColor = [UIColor blackColor];
    }
    
    //任务参与人，要把报障人算进去
    NSInteger showCount = 1;
    NSInteger observerCount = reportTrouble.observers.count;
    NSMutableArray * observerMur = [NSMutableArray arrayWithArray:reportTrouble.observers];//将参与者拿出来
    NSMutableArray * observerIds = [NSMutableArray array];
    [observerMur enumerateObjectsUsingBlock:^(YWHandler* _Nonnull handler, NSUInteger idx, BOOL * _Nonnull stop) {
        [observerIds addObject:@(handler.uniqueId)];
    }];
    if (observerCount) {
        NSPredicate *searchPredicate = [NSPredicate predicateWithFormat:@"%K = %ld", @"uniqueId", fromUser.uniqueId];
        NSArray *array = [[reportTrouble.observers filteredArrayUsingPredicate:searchPredicate] mutableCopy];
        if (array.count==1) {
            observerCount--;
            [observerIds removeObject:@(fromUser.uniqueId)];
        }
        showCount = showCount + observerCount;
    }
    NSString * firstStr = [NSString stringWithFormat:@"参与人(%ld): ",(long)showCount];
    
    [observerMur removeAllObjects];
    NSMutableString *observerName = [[NSMutableString alloc] init];
    if (observerIds.count) {
        for (id obj in observerIds ) {
            NSInteger uniqueId = [obj integerValue];
            YWHandler *handler = [[YWContactManager shareManager] getHandlerWithUniqueId:uniqueId];
            [observerMur addObject:handler];
        }
    }
    [observerMur enumerateObjectsUsingBlock:^(YWHandler*  _Nonnull handler, NSUInteger idx, BOOL * _Nonnull stop) {
        if (observerName.length && idx!=0) {
            [observerName appendString:@" "];
        }
        [observerName appendString:handler.userName];
    }];
    
    NSString * nameStr = [NSString stringWithFormat:@"%@ %@",name?:@"",observerName?:@""];//参与者要加进来

    self.observersLabel.attributedText = [YWCommonTool attributedTextWithFirstText:firstStr firstColor:[UIColor customTextGrayBlackColor] secondText:nameStr secondColor:[UIColor customBlueColor] font:kContentFont];
    //评论，如果没有评论，那么要重新设置约束
    //有评论
    NSArray *commentArray = [[YWReplyManager alloc] replysWithtRelationId:_reportTrouble.troubleId andRelationType:YWReplyRelationTypeTrouble];
    if (commentArray.count>0) {
        YWReply * reply = [commentArray firstObject];
        NSString * replyCount = [NSString stringWithFormat:@"评论(%ld): ",commentArray.count];
        //    时间
        NSString * timeStr = [YWCommonTool recordDateByFormatTimeString:reply.replyTime/1000 showYear:YES];
        NSString * timeText = [NSString stringWithFormat:@"  %@",timeStr];
        //    内容
        NSString *replyName = [NSString stringWithFormat:@"%@: ",reply.replier.userName];
        NSString *atUserName = reply.atUser.userName.length>0?[NSString stringWithFormat:@" @%@",reply.atUser.userName]:@"";
        NSString * content = atUserName.length?[NSString stringWithFormat:@" %@  ",reply.content.length>0?reply.content:@""] : (reply.content.length>0?reply.content:@"");
        
        self.replyLabel.attributedText = [YWCommonTool attributedTextWithFirstText:replyCount firstColor:[UIColor customTextGrayColor] firstFont:kContentFont secondText:replyName secondColor:[UIColor customBlueColor] secFont:kContentFont thirdText:atUserName thirdColor:[UIColor customBlueColor] thirdFont:kContentFont fourthText:content fourthColor:[UIColor blackColor] fourFont:kContentFont fifthText:timeText fifthColor:[UIColor customTextGrayColor] fifthFont:[UIFont systemFontOfSize:13]];
    }else{
        self.replyLabel.attributedText = nil;
    }
    self.note.preferredMaxLayoutWidth = self.note.frame.size.width;
    self.equipmentLabel.preferredMaxLayoutWidth = self.equipmentLabel.frame.size.width;
    self.location.preferredMaxLayoutWidth = self.location.frame.size.width;
    self.observersLabel.preferredMaxLayoutWidth = self.observersLabel.frame.size.width;
    self.replyLabel.preferredMaxLayoutWidth = self.replyLabel.frame.size.width;
}

-(NSString *)stateString{
    YWTroubleMissionStatus state = _reportTrouble.troubleStatus;
    switch (state) {
        case YWTroubleMissionStatusUnAssign:
            _stateString = @"未分配";
            break;
        case YWTroubleMissionStatusAssign:
            _stateString = @"已分配";
            break;
        case YWTroubleMissionStatusFinish:
            _stateString = @"已完成";
            break;
        case YWTroubleMissionStatusCancelPostTrouble:
            _stateString = @"已取消";
            break;
    }
    return _stateString;
}


- (void)setUpSubviews {
    
    UIView *superview = self.contentView;
    /**
     *  头像 名字    状态
     *  头像 时间
     */
    [self.reporterImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.and.top.mas_equalTo(superview).offset(8);
        make.width.and.height.mas_equalTo(@46);
    }];
    
    [self.reporterName mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(_reporterImageView.mas_centerY).offset(-2);
        make.left.mas_equalTo(_reporterImageView.mas_right).offset(6);
    }];
    
    [self.createTime mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(_reporterName);
        make.top.mas_equalTo(_reporterName.mas_bottom).offset(4);
    }];
    
    [self.stateLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.baseline.mas_equalTo(_reporterName.mas_baseline);
        make.right.mas_equalTo(superview).offset(-8);
    }];
    /**
     *  编号
     *  设备
     *  位置
     *  说明
     *  图片集
     */
    [self.bianhao mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_reporterImageView.mas_bottom).offset(6);
        make.left.mas_equalTo(superview).offset(8);
        make.right.mas_equalTo(superview).offset(-8);
    }];
    
    [self.equipmentLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_bianhao.mas_bottom).offset(6);
    }];

    [self.location mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_equipmentLabel.mas_bottom).offset(6);
        
    }];

    [self.note mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_location.mas_bottom).offset(6);
        make.left.and.right.mas_equalTo(@[_bianhao,_equipmentLabel,_location]);
//        make.bottom.mas_equalTo(superview).offset(-8);
    }];
    
    [self.separatorLineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_note.mas_bottom).offset(6);
        make.left.and.right.mas_equalTo(superview);
        make.height.mas_equalTo(@1.0);
    }];
    
    [self.observersLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.separatorLineView.mas_bottom).offset(6);
        make.left.and.right.mas_equalTo(_bianhao);
    }];
    [self.replyLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.observersLabel.mas_bottom).offset(6);
        make.left.and.right.mas_equalTo(_bianhao);
        make.bottom.mas_equalTo(superview).offset(-6);
    }];
//    [self.picturesView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.mas_equalTo(_note.mas_bottom).offset(6);
//        make.left.and.right.mas_equalTo(@[_bianhao,_equipmentLabel,_location,_note]);
//        _picHeightConstraint = make.height.mas_equalTo(@90);
//        make.bottom.mas_equalTo(superview);
//    }];
}

//- (void)layoutSubviews{
//    [super layoutSubviews];
//    
//}

- (YYLabel *)stateLabel{
    if (!_stateLabel) {
        YYLabel *label = [[YYLabel alloc] init];
        label.font = kContentFont;
        _stateLabel = label;
        [self.contentView addSubview:_stateLabel];
    }
    return _stateLabel;
}

- (UIImageView *)reporterImageView{
    if (!_reporterImageView) {
        UIImageView *imageView = [UIImageView new];
        imageView.clipsToBounds = YES;
        imageView.layer.cornerRadius = 46/2;
        _reporterImageView = imageView;
        [self.contentView addSubview:_reporterImageView];
    }
    return _reporterImageView;
}

- (YYLabel *)reporterName{
    if (!_reporterName) {
        YYLabel *label = [[YYLabel alloc] init];
        label.font = kContentFont;
        label.textColor = [UIColor customYellowColor];
        _reporterName = label;
        [self.contentView addSubview:_reporterName];
    }
    return _reporterName;
}

- (YYLabel *)createTime{
    if (!_createTime) {
        YYLabel *label = [[YYLabel alloc] init];
        label.font = kContentFont;
        label.textColor = [UIColor customTextGrayBlackColor];
        _createTime = label;
        [self.contentView addSubview:_createTime];
    }
    return _createTime;
}

- (YYLabel *)bianhao{
    if (!_bianhao) {
        YYLabel *label = [[YYLabel alloc] init];
        _bianhao = label;
        [self.contentView addSubview:_bianhao];
    }
    return _bianhao;
}

- (YYLabel *)equipmentLabel{
    if (!_equipmentLabel) {
        YYLabel *label = [[YYLabel alloc] init];
        label.numberOfLines = 0;
        _equipmentLabel = label;
        [self.contentView addSubview:_equipmentLabel];
    }
    return _equipmentLabel;
}

- (YYLabel *)location{
    if (!_location) {
        YYLabel *label = [[YYLabel alloc] init];
        label.numberOfLines = 0;
        _location = label;
        [self.contentView addSubview:_location];
    }
    return _location;
}

- (YYLabel *)note{
    if (!_note) {
        YYLabel *label = [[YYLabel alloc] init];
        label.numberOfLines = 0;
        _note = label;
        [self.contentView addSubview:_note];
    }
    return _note;
}

//- (UIView*)separatorLineView{
//    if (!_separatorLineView) {
//        UIView *view = [[UIView alloc] init];
//        view.backgroundColor = [UIColor customBackgroudColor];
//        _separatorLineView = view;
//        [self.contentView addSubview:_separatorLineView];
//    }
//    return _separatorLineView;
//}
//
//- (YYLabel*)observersLabel{
//    if (!_observersLabel) {
//        YYLabel *label = [[YYLabel alloc] init];
//        label.numberOfLines = 0;
//        _observersLabel = label;
//        [self.contentView addSubview:_observersLabel];
//    }
//    return _observersLabel;
//}
//
//- (YYLabel*)replyLabel{
//    if (!_replyLabel) {
//        YYLabel *label = [[YYLabel alloc] init];
//        label.numberOfLines = 0;
//        _replyLabel = label;
//        [self.contentView addSubview:_replyLabel];
//    }
//    return _replyLabel;
//}
//-(GropPictureView *)picturesView{
//    if (!_picturesView) {
//        GropPictureView *gropPictureView = [GropPictureView new];
//        _picturesView = gropPictureView;
//        [self.contentView addSubview:_picturesView];
//    }
//    return _picturesView;
//}



@end
